﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.AP.Enums;
using UFIDA.U9.CBO.FI.Enums;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.SM.SO;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.CusDev.QJKJPlugInBE
{
    class ProcessForSOInserting : IEventSubscriber
    {
        public void Notify(params object[] args)
        {

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;

            if (key == null || key.GetEntity() == null) return;
            //销售订单
            UFIDA.U9.SM.SO.SO so = key.GetEntity() as UFIDA.U9.SM.SO.SO;
            if (so == null) return;

            #region 销售订单保存时验证立账位置=付款客户，不等时报异常“立账位置和付款位置必须一样”
            //判断销售订单是否为开立
            if(so.Status == SODocStatusEnum.Open)
            {
                String sql = $@"SELECT  max(Code) Code from  Base_User where Name ='{so.CreatedBy}' GROUP BY Name ";
                DataSet ds = null;
                DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out ds);
                if (ds == null || ds.Tables == null || ds.Tables.Count == 0 || ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0 || ds.Tables[0].Rows[0] == null)
                {
                    return;
                }
                else
                {
                    so.DescFlexField.PrivateDescSeg9 = ds.Tables[0].Rows[0][0].ToString();
                }
                foreach (var line in so.SOLines)
                {
                      //判断行立账位置跟付款客户必须一样
                    if (line.BillToSite.CustomerSite.Code != so.PayerSite.CustomerSite.Code)
                    {
                        throw new Exception("销售订单行立账位置跟付款客户必须一样");
                    }
                    //判断行信用客户位置跟付款客户必须一样
                    else if (line.CreditObj.CustomerSite.Code != so.PayerSite.CustomerSite.Code)
                    {
                        throw new Exception("销售订单行信用客户位置跟付款客户必须一样");
                    }
                    else
                    {
                        return;
                    }


                }
            }

            #endregion

        }

    }
}
